package org.wpahs.ahn.rssfeed;

import android.content.Context;
import java.util.ArrayList;
import java.util.List;

/**
 * wow great
 * Created by dgambone on 02/24/2015.
 */
public class Downloader {
    public enum DownloadType {
        FeedImage,FeedItemImage
    }
    private static int countBeingProcessed=0;
    private static Context mContext;
    static int max = 3;

    private static List<Image> imagesQueue = new ArrayList<>();

    public static void addImageToQueue(Context context,Image image){
        synchronized (Downloader.class) {
            mContext = context;
            imagesQueue.add(image);
        }
        processQueue();
    }

    public static void removeImageFromQueue(Image image){
        synchronized (Downloader.class) {
            for (Image img : imagesQueue) {
                if (img.getId() == image.getId() && img.getSubId() == image.getSubId()) {
                    imagesQueue.remove(img);
                    countBeingProcessed--;
                    break;
                }
            }
        }
        processQueue();
    }

    private static void processQueue(){
        synchronized (Downloader.class) {
            if(countBeingProcessed >= max) return;
            for (int idx = 0; idx < imagesQueue.size(); idx++) {
                Image img = imagesQueue.get(idx);
                if (!img.isBeingProcessed()) {
                    img.setBeingProcessed(true);
                    new DownloadImage(mContext, img).execute();
                    countBeingProcessed++;
                }
                if (countBeingProcessed >= max) break;
            }

        }
    }




}
